package com.bkitmobile.kesu.android.GUI;

import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.appenginefan.toolkit.common.ClientSocketSubstitute;
import com.bkitmobile.kesu.android.connectServer.*;

public class Login extends Activity implements  OnClickListener{
	private static String id, pass;
	private Button btnLogin, btnRegister;
	private ImageView image;
	private Drawable imgSleep, imgWakeUp;
	//private ProgressDialog dialog; 
	private CheckBox checkInvi;
	private Handler handler = new Handler();
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        Resources res = getResources();
        imgSleep = res.getDrawable(R.drawable.login);
        imgWakeUp = res.getDrawable(R.drawable.logining);
        image = (ImageView) findViewById(R.id.login_image);
        image.setImageDrawable(imgSleep);
        
        btnLogin = (Button) findViewById(R.id.login_login);
        btnRegister = (Button) findViewById(R.id.login_register);
        checkInvi = (CheckBox) findViewById(R.id.login_checkboxInvisible);
        btnLogin.setOnClickListener(this);
        btnRegister.setOnClickListener(this);
    }
	
	public void onClick(View v) {
		EditText txtID, txtPass;
		//showDialog(0);
		//dialog.show();
        txtID = (EditText) findViewById(R.id.login_name);
        txtPass = (EditText) findViewById(R.id.login_pass);
        
		if(btnLogin == (Button)v){
			id = txtID.getText().toString().trim();
			pass = txtPass.getText().toString().trim();
			if(id.equals("")){
				Toast.makeText( this, getString(R.string.login_toast_inputID), Toast.LENGTH_LONG).show();
			}
			else if(pass.equals("")){
				Toast.makeText( this, getString(R.string.login_toast_inputPass), Toast.LENGTH_LONG).show();
			}
			else{
				//TODO: do something eg. [check ID and Pass]
				//setProgressBarIndeterminateVisibility(true);
				image.setImageDrawable(imgWakeUp);
				String []identities = {"ID", "username", "password", "invisible"};
				String []atributies = {Request.LOGIN, id, pass, (checkInvi.isChecked()?"invisible":"available")};
			    Request.sendAndRecieveData(identities, atributies, true,this,new ServiceCallback<String>() {
					
					@Override
					public void onSuccess(final String result) {
						// TODO Auto-generated method stub
						handler.post(new Runnable() {
							
							@Override
							public void run() {
								// TODO Auto-generated method stub
								 Log.d("Login", result);
								    boolean state = (checkInvi.isChecked()
						    				?FriendsList.INVISIBLE:FriendsList.ONLINE);
								    Log.d("State first", state+"");
								    JSONObject object = null;
								    try {
										object = new JSONObject(result);
								    if (object.getString("result").startsWith("succ"))
								    {
								    	Toast toast = Toast.makeText(Login.this, getString(R.string.login_success), Toast.LENGTH_SHORT);
								    	toast.show();
								    	Intent intent = new Intent(Login.this, FriendsList.class);
								    	intent.putExtra("list", result);
								    	intent.putExtra("username", id);
								    	Log.d("state login", state+"");
								    	intent.putExtra("state", state);
								    	staticClass.user = id;
								    	 try {
								 			staticClass.socket = new ClientSocketSubstitute(
								 					 	new URL(staticClass.socketURL),   // Connection URL
								 			            1000,                     // ping frequency
								 			            5                         // max. messages per ping
								 			        );
								 		} catch (MalformedURLException e1) {
								 			e1.printStackTrace();
								 		}
								    	startActivity(intent);
								    	finish();
								    } else if (object.getString("result").startsWith("logged"))
								    {
								    	ConfirmLoginDlg dlg = new ConfirmLoginDlg(id, Login.this,state);
								    	dlg.show();
								    }
								    else 
								    {
								    	image.setImageDrawable(imgSleep);
								    	StaticDialogs.okButtonDialog(Login.this, object.getString("result"));
								    	return;
								    }
								    } catch (JSONException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
							}
						});
						
					}
					@Override
					public void onFailure(Exception exception) {
						// TODO Auto-generated method stub
						handler.post(new Runnable() {
							
							@Override
							public void run() {
								// TODO Auto-generated method stub
								StaticDialogs.okButtonDialog(Login.this
										, Login.this.getString(R.string.disconnect));
							}
						});
						
						
					}
				});
			   
			}
		}
		else if(btnRegister == (Button)v){
			startActivity(new Intent(this, Register.class));
		}
	}
	
	
	public static String getID(){
		return id;
	}
	public static String getPass(){
		return pass;
	}
	public static void setPass(String newPass){
		pass = newPass;
	}
	
}